package com.fafa.swing.base;

import javax.swing.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

/**
 * @author : fafa
 * @version V1.0
 * @Project: SwingTest
 * @Package com.fafa.swing
 * @Description: JPopupMenuDemo
 * @date Date : 2019年11月25日 22:21
 */
public class JPopupMenuDemo extends JFrame {

    JMenu fileMenu;
    JPopupMenu jPopupMenuOne;
    JMenuItem openFile,closeFile,exit;
    JRadioButtonMenuItem copyFile,pasteFile;
    ButtonGroup buttonGroupOne;

    public JPopupMenuDemo(){
        jPopupMenuOne = new JPopupMenu();
        buttonGroupOne = new ButtonGroup();
        //创建文件菜单及子菜单，并将子菜单添加到文件菜单中
        fileMenu = new JMenu("文件");
        openFile = new JMenuItem("打开");
        closeFile = new JMenuItem("关闭");
        fileMenu.add(openFile);
        fileMenu.add(closeFile);
        //将fileMenu添加到弹出式菜单中
        jPopupMenuOne.add(fileMenu);
        //添加分隔符
        jPopupMenuOne.addSeparator();
        //创建单选菜单选项，并添加到ButtonGroup对象中
        copyFile = new JRadioButtonMenuItem("复制");
        pasteFile = new JRadioButtonMenuItem("粘贴");
        buttonGroupOne.add(copyFile);
        buttonGroupOne.add(pasteFile);
        //将copyFile添加到jPopMenuOne中
        jPopupMenuOne.add(copyFile);
        jPopupMenuOne.add(pasteFile);
        jPopupMenuOne.addSeparator();

        exit = new JMenuItem("退出");
        jPopupMenuOne.add(exit);
        //创建监听器对象
        MouseListener popupListener = new PopupListener(jPopupMenuOne);
        //向主窗口注册监听器
        this.addMouseListener(popupListener);
        this.setTitle("弹出式菜单");
        this.setBounds(500,500,400,200);
        this.setVisible(true);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

    class PopupListener extends MouseAdapter{
        JPopupMenu jPopupMenu;
        PopupListener(JPopupMenu jPopupMenu){
            this.jPopupMenu = jPopupMenu;
        }
        public void mousePressed(MouseEvent e){
            showPopupMenu(e);
        }
        public void mouseReleased(MouseEvent e){
            showPopupMenu(e);
        }
        public void showPopupMenu(MouseEvent e){
            if(e.isPopupTrigger()){
                jPopupMenu.show(e.getComponent(), e.getX(), e.getY());
            }
        }
    }

    public static void main(String[] args) {
        new JPopupMenuDemo();
    }
}
